var min_height = 850;
var main_min_height = 1000;
var bottom_space = 450;
var debug = false;
var X = 0;
var Y = 0;
var js_loaded = [];
//var devmode = false;
//section_header_loaded = 0;

var Browser = {
		  Version: function() {
		    var version = 999; // we assume a sane browser
		    if (navigator.appVersion.indexOf("MSIE") != -1)
		      // bah, IE again, lets downgrade version number
		      version = parseFloat(navigator.appVersion.split("MSIE")[1]);
		    return version;
		  }
		}
/*
document.onmousemove=function(e) {
    if (navigator.appName == "Microsoft Internet Explorer") { 
    	if (Browser.Version() >= 9) {
    		X = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft; 
    		Y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
    	}
	} else  {
		X = e.pageX;
		Y = e.pageY;
	}
    
    if (window.sessionStorage.drag==1 && window.sessionStorage.username != null) {
    if (navigator.appName == "Microsoft Internet Explorer") { 
        window.sessionStorage.toolbarX = event.clientX + document.body.scrollLeft;
		 } else  window.sessionStorage.toolbarX = e.pageX;
		 window.sessionStorage.toolbarX -= 250;
    }
   if(typeof move_toolbar == 'function') move_toolbar ();
}
*/
//Contectual menus

if (document.addEventListener) {
	document.addEventListener('contextmenu', function(e) {
		e.preventDefault();
		context_menus (e);
        
    }, false);
} else {
	//IE 7 and 8 support
    document.attachEvent('oncontextmenu', function() {
    	window.event.returnValue = false;
    	context_menus ();
        
    });

}


function getImgBySrc (src) {
	var obj = {};
	var imgs = document.getElementsByTagName("img");
	for (i=0; i<imgs.length; i++) {
		if (imgs[i].src == src) {
			obj =  imgs[i];
		}
	}
	return obj;
}


function show_image_alignment_menu ( ) { 
	var image_alignment_menu = document.getElementById("image_alignment_menu");
	//image_alignment_menu.style.top = Y + "px";
	//image_alignment_menu.style.left = X + "px";
	
	
	if (image_alignment_menu.style.display == "block") image_alignment_menu.style.display = "none";
	else image_alignment_menu.style.display = "block";
	
}

function findPosition( oElement ) {
	  if( typeof( oElement.offsetParent ) != 'undefined' ) {
	    for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) {
	      posX += oElement.offsetLeft;
	      posY += oElement.offsetTop;
	    }
	    return [ posX, posY ];
	  } else {
	    return [ oElement.x, oElement.y ];
	  }
	}

function context_menus (e) {
	
	if (window.event) e = window.event; 
    var element = e.srcElement? e.srcElement : e.target; 
    if ((window.sessionStorage.username != null) && (getElementId(element) == "content_text")) {
    	if (element.tagName == "IMG") {
    		var img = getImgBySrc (element.src);
    	//	img.style.cssFloat  = "right";
    		if (img.style.cssFloat  == "left")  img.style.cssFloat  = "none";
    		else if (img.style.cssFloat  == "none")  img.style.cssFloat  = "right";
    		else img.style.cssFloat  = "left";
    		
    	}
    } else if ((window.sessionStorage.username != null) && (getElementId(element) == "section_header")) {
    	var loaded = add_js ("/modules/section_header/admin/functions.js");
    	wait_for_load ("/modules/section_header/admin/functions.js","add_edit_elements()");
    }
   
}

function wait_for_load (filename, scriptname) {
	
	var scripts = document.getElementsByTagName('script');
	var found = 0;
	//alert (scripts.length);
	for (var i=0; i < scripts.length; i++) {
		//alert(scripts[i].src + " : " + location.hostname + filename );
		var url = "http://" + location.hostname + filename;
		if (scripts[i].src == url) found = 1;
	}
	
	//alert("found:"+ found);
	if ((typeof(section_header_loaded) != "undefined")&&(section_header_loaded == 1)) eval (scriptname);
	else  var t = setTimeout ( "wait_for_load ('" + filename + "','" + scriptname + "')", 100 );

}

function getElementId (element,depth) {
    if (isNaN(depth)) depth = 0;
    depth++;
    if (depth>20) return "undefined";
    if (element == null) return "";
		else {
    		 if ((element.id != "")&&(element.id in {"toolbar_drag":"","content_text":"","body":"","section_header":"","navmenu":"","content":"","menu_top_inner":""})) {
				  return element.id;
    //if (element.id != "") return element.id;
    		 } else return getElementId (element.parentNode,depth);
		}
}


function add_css (href) {
    var fileref=document.createElement("link")
    fileref.setAttribute("rel", "stylesheet")
    fileref.setAttribute("type", "text/css")
    fileref.setAttribute("href", href)
    document.getElementsByTagName("head")[0].appendChild(fileref)
}

function add_js (filename, version) {
	version = typeof(version) != 'undefined' ? version : 0.01;
    var fileref=document.createElement('script');
    fileref.setAttribute("type","text/javascript");
    fileref.setAttribute("src", filename + "?version=" + version);
    //fileref.setAttribute("src", filename);
    document.getElementsByTagName("head")[0].appendChild(fileref);
    /*
	if (! in_array (filename, js_loaded)) {
	   var head= document.getElementsByTagName('head')[0];
	   var script= document.createElement('script');
	   script.type= 'text/javascript';
	   //script.onload = js_loaded.push( filename);
	   script.src= filename;
	   head.appendChild(script);
	   return true;
	}
	return false;
	*/
}

function getFile(url) {
  if (window.XMLHttpRequest)  AJAX=new XMLHttpRequest();              
  else  AJAX=new ActiveXObject("Microsoft.XMLHTTP");
  
  if (AJAX) {
	 var myRegExp1 = /.php/;
	 var matchPos1 = url.search(myRegExp1);
	 
	 if (matchPos1>0) {
		 var myRegExp2 = /\?/;
		 
	     var id = Math.floor(Math.random()*10000);
	     var matchPos2 = url.search(myRegExp2);
		 if (matchPos2>0)  url = url + "&refresh_id=" + id;
		 else url = url + "?refresh_id=" + id;
	 }
	 
	 
	 var params = url.split("?");
	 
     AJAX.open("POST", params[0] , false); 
     AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
     //AJAX.setRequestHeader( "Cache-Control:" , "no-store, no-cache, must-revalidate");
     //AJAX.setRequestHeader( "Pragma","no-cache" );
     
     AJAX.send(params[1]);
     return AJAX.responseText;                                         
  } else  return false;                                          
}









function getXML(url) {
	  if (window.XMLHttpRequest)  AJAX=new XMLHttpRequest();              
	  else  AJAX=new ActiveXObject("Microsoft.XMLHTTP");
	  
	  if (AJAX) {
		  
	     AJAX.open("GET", url, false);            
	     //AJAX.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
	     
	     //header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
	     //AJAX.setRequestHeader( "Cache-Control:" , "no-store, no-cache, must-revalidate");
	     //header("Cache-Control: post-check=0, pre-check=0", false);
	    // AJAX.setRequestHeader( "Pragma","no-cache");
	     AJAX.send(null);
	     return AJAX.responseXML;                                         
	  } else  return false;                                          
	}

function postFile(url, params) {
	  if (window.XMLHttpRequest)  AJAX=new XMLHttpRequest();              
	  else  AJAX=new ActiveXObject("Microsoft.XMLHTTP");
	  
	  if (AJAX) {
	     AJAX.open("POST", url, false);   
	     AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	     AJAX.setRequestHeader("Content-length", params.length);
	     AJAX.setRequestHeader("Connection", "close");
	     
	     AJAX.send(params);
	     return AJAX.responseText;                                         
	  } else  return false;                                          
	}



function get_height (obj_id) {
				 var objHeight = 0;
				 var obj = document.getElementById(obj_id)||new Object();
				 if ("clientHeight" in obj) objHeight = obj.clientHeight;
				 else if ("offsetHeight" in obj) objHeight = obj.offsetHeight;
				 //if (debug) console.log(obj_id + " " + objHeight);
				 return objHeight;
}

Array.prototype.max = function() {
    var max = this[0];
		var len = this.length;
		for (var i = 1; i < len; i++) if (this[i] > max) max = this[i];
		return max;
}

function set_height() {
				 var p_height =  min_height;
				 if (file=="") p_height = main_min_height;
				 //Set body height according to articles and nav bar
				 var body = document.getElementById("body");
				 
				 
				 var heights = new Array (
  							 get_height("navmenu"),
				 				 get_height("content"), 
								 get_height("info_bar")
				 );
				 
				 var bodyHeight = get_height("body");
				 
				 bodyHeight = heights.max();
				 if (bodyHeight == 0) bodyHeight = p_height;
				 else bodyHeight += bottom_space;
				 
				 //if (debug) console.log("initial bodyHeight: " + bodyHeight);
				 
				 
				 
         
				 //bodyHeight =  bodyHeight * 2;
				 //if (bodyHeight < min_height) bodyHeight = min_height;
				 
				 body.style.height = bodyHeight + "px";
				 
				 //set graphic height
				 var vinnerbar = document.getElementById("vinnerbar");
				 var vbar = document.getElementById("vbar");
				 
				 var vheight = bodyHeight + 150;
				 //vinnerbar.style.height = body.style.height;
				 
				 
				 if(vinnerbar != null)  vinnerbar.style.height = vheight - 165 + "px";
				 if(vbar != null) vbar.style.height = vheight + "px";
				 
				 var bg_right = document.getElementById("bg_right");
				 var bg_right_height = get_height("header") + bodyHeight + get_height("footer");
				 
				 bg_right.style.height = bg_right_height + "px";
				 //var windowHeight = window.outerheight  ? window.outerheight  : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
				// document.body.style.height = bg_right_height + "px";
         //document.getElementById("footer").style.top = f_scrollTop + "px";
		     //alert(window.location.href);
				 //var content_text = document.getElementById("content_text");
				 //console.log (get_height("content_text"));
}

function setAjaxParameter(ajax_parameter , ajax_value) {
	var result = getFile("/modules/general/set_ajax_parameter.php?ajax_parameter=" + ajax_parameter + "&ajax_value=" + ajax_value);
}

function getAjaxParameter(ajax_parameter) {
	var result = getFile("/modules/general/get_ajax_parameter.php?ajax_parameter=" + ajax_parameter);
	return result;
}

function base64_encode (data) {
    // Encodes string using MIME base64 algorithm  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/base64_encode    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Pellentesque Malesuada    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
    // mozilla has this native    // - but breaks in 2.0.0.12!
    //if (typeof this.window['atob'] == 'function') {
    //    return atob(data);
    //}
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";    
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
        ac = 0,
        enc = "",
        tmp_arr = [];
     if (!data) {
        return data;
    }
 
    data = this.utf8_encode(data + ''); 
    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++); 
        bits = o1 << 16 | o2 << 8 | o3;
 
        h1 = bits >> 18 & 0x3f;
        h2 = bits >> 12 & 0x3f;        h3 = bits >> 6 & 0x3f;
        h4 = bits & 0x3f;
 
        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);    } while (i < data.length);
 
    enc = tmp_arr.join('');
 
    switch (data.length % 3) {    case 1:
        enc = enc.slice(0, -2) + '==';
        break;
    case 2:
        enc = enc.slice(0, -1) + '=';        
        break;
    }
 
    return enc;
}

function utf8_encode (argString) {
    // Encodes an ISO-8859-1 string to UTF-8  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/utf8_encode    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'    
	var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
    var utftext = "", start, end, stringl = 0;
 
    start = end = 0;    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
         if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.slice(start, end);            }
            utftext += enc;
            start = end = n + 1;
        }
    } 
    if (end > start) {
        utftext += string.slice(start, stringl);
    }
     return utftext;
}

function img_align_left(src) {
        var selObj = (document.all)? document.selection.createRange() : document.getSelection();
        
        
        alert(selObj)
	//var img = getImgBySrc ();
	//img.style.cssFloat  = "left";	
}
function img_align_right() {
	//var img = getImgBySrc (src);
	//img.style.cssFloat  = "right";
        var selObj = (document.all)? document.selection.createRange() : document.getSelection();
        alert(selObj)
	
}
function img_align_center() {
        var selObj = (document.all)? document.selection.createRange() : document.getSelection();
        alert(selObj)
	//var img = getImgBySrc (src);
	//img.style.cssFloat  = "clear";
}

function in_array (needle, haystack) {
	for (key in haystack) if (haystack[key] == needle)  return true;
    return false;
}


function move_toolbar () {
	   if (window.sessionStorage.username != null) {
		  
			
				 
	   		var admin_toolbar =  document.getElementById("admin_toolbar");
	   		//console.log( window.sessionStorage.toolbarX );
	 	       try { if (admin_toolbar != null) admin_toolbar.style.left = window.sessionStorage.toolbarX ;}
                       catch (err) {}
	   }
	}
//if(typeof move_toolbar == 'function') move_toolbar ();
move_toolbar ();



